"use strict";
define(["commonUI", "getTime", "laydate", "template","global","select2", "datatables"], function (
    commonUI, getTime, laydate, template,global
) {
    var project = null;
    var user = null;
    var standardTable;
    var param = {
        pageNumber: 1,
        pageSize: 10
    };
    var app = {
        init: function () {
            if(!global.existCurrProject()){
                return;
            }
            project = global.getCurrProject();
            user = global.getLoginUser();
            this.initText();
            this.eventBind();
            // getTime.resize();
            getTime.getNowDate();
            getTime.getTimeInfo();
            this.initSelect();
            this.initTable();
        },
        /**
        * 渲染文字内容
        */
         initText: function() {
            //用户名显示
            $(".name").text(user.userName)
        },
        // 搜索条件初始化
        initSelect: function () {
            global.get("/web/project/listByUser",response=>{
                if(response.success){
                    var data = [];
                    response.data.projects.forEach(element => {
                        var item = {};
                        item.id=element.id;
                        item.text=element.name;
                        data.push(item)
                    });
                    $('#project').select2({
                        //  minimumResultsForSearch设置为-1，去除搜索框 
                        width: 250,
                        minimumResultsForSearch:-1,
                        allowClear: true,
                        placeholder:"请选择项目",
                        data:data
                    });
                }else{
                    alert(response.message)
                }
            });
        },
        // 表格初始化
        initTable: function () {
            standardTable = $("#standard_table").DataTable({
                // 关闭搜索功能
                processing: true,
                searching: false,
                serverSide: true,
                destroy: true,
                ordering: false,
                // scrollY: 600,
                // scrollCollapse: true,
                columns: [
                //     {
                //     title: "<div id=\"select-checkbox\" class=\"select-checkbox1\"></div>",
                //     data: "checkBox",
                //     width: 20
                // },
                {
                    title: "序号",
                    data: "number",
                    width: "100px",
                }, 
                {
                    title: "用户名",
                    data: "userName",
                    width: "80px",
                    render: function (data, type, full, meta) {//其中data代表本列数据，full代表本行所有数据
                        $(standardTable.row(meta.row).node()).data("nodeDetail", JSON.stringify(full));
                        return "<div class=\"text-overflow\" title=\"" + data + "\">" + data + "</div>";
                    }
                }, 
                // {
                //     title: "密码",
                //     data: "plaintextPassword",
                //     width: "80px"
                // },
                 {
                    title: "用户角色",
                    data: "roleName",
                    width: "80px"
                }, {
                    title: "所属项目",
                    data: "projectNames1",
                    width: "30%"
                }, {
                    title: "备注",
                    data: "description",
                    width: "10%"
                }, {
                    title: "锁定状态",
                    data: "locked",
                    width: "80px",
                    render:function(data,type,full){
                        if(data==0){
                            return "未锁定"
                        }else{
                            return "已锁定"
                        }
                    }
                },{
                    title: "操作",
                    width: "220px",
                    render: function (data, type, full, meta) { //其中data代表本列数据，full代表本行所有数据
                        return '<button type="button" class="btn btn-warning btn-sm editData">修改</button>' + 
                        '<button type="button" class="btn btn-warning btn-sm delData" userId="'+full.id+'">删除</button>' + 
                        '<button type="button" class="btn btn-warning btn-sm relateData" userId="'+full.id+'">关联项目</button>'+
                        '<button type="button" class="btn btn-warning btn-sm modifyPassword" userId="'+full.id+'">修改密码</button>';
                    }
                }],
                columnDefs: [
                //     {
                //     className: "select-checkbox ",
                //     targets: 0
                // },
                 {
                    // targets 同时制定多个列时，可以传递数组（比如[1,2]）;制定所有传"_all"  
                    targets: [1, 2, 3, 4, 5],
                    render: function (data, type, full, meta) { //其中data代表本列数据，full代表本行所有数据
                        return "<div class=\"text-overflow\" title=\"" + data + "\">" + data + "</div>";
                    }
                }],
                select: {
                    // 可选择的配置有： 'api'、'single'、'multi'、'os'、'multi+shift'
                    style: "multi",
                    // 控制是否在左下角显示选中信息
                    info: false,
                    selector: "td:first-child",
                    orderable: false
                },
                language: {
                    sEmptyTable: "<div class=\"blank-icon\"><p class=\"msg\"><i class=\"aidicon aidicon-emoticon-sad\"></i> 没有搜到任何数据</p></div>"
                },
                ajax: function (params, callback, setting) {
                    param.pageNumber = (params.start / params.length) + 1;
                    param.pageSize = params.length;
                    param.projectId = $("#project").val();
                    param.usernameSearch = $("#optUser").val()
                    global.get("/web/userManage/list",function (res) {
                        if (res.success) {
                            var obj = {};
                            obj.data = res.data.page.content;
                            obj.draw = params.draw;
                            obj.recordsTotal = res.data.page.totalElements;
                            obj.recordsFiltered = res.data.page.totalElements;
                            callback(obj);
                            }
                        },param);
                },
                initComplete: function (settings, json) {

                }
            });
            // 勾选其中一项
            standardTable.on("select", function (e, dt, type, indexs) {
                var ruleId = $("#standard_table_wrapper tbody tr").eq(indexs).find(".text-blue").attr("ruleId");
                // 选中行数
                var selectedLength = standardTable.rows({
                    selected: true
                }).count();
                // 所有行数行数
                var allLength = standardTable.rows().count();
                selectedLength === allLength && $("#standard_table_wrapper thead>tr>.select-checkbox").addClass("selected");
                // var selectedDoms = standardTable.rows(".selected").data();
                
            });
            // 去掉选中
            standardTable.on("deselect", function (e, dt, type, indexs) {
                $("#standard_table_wrapper thead>tr>.select-checkbox").removeClass("selected");
            });
            // 点击全选
            $("#standard_table_wrapper .select-checkbox1").click(function (e) {
                var $parent = $(this).parent("th");
                $parent.toggleClass("selected");
                if ($parent.hasClass("selected")) {
                    $(this).parents("#standard_table_wrapper").find("tbody tr").each(function (i) {
                        standardTable.row(i).select();
                    });
                } else {
                    $(this).parents("#standard_table_wrapper").find("tbody tr").each(function (i) {
                        standardTable.row(i).select(false);
                    });
                }
            });
        },
        /** 事件绑定 */
        eventBind: function () {
            // 新增弹窗
            $(document).on("click", "#addData", function () {
                Dialog.open({
                    title: "新增",
                    theme: "formDialog",
                    width: 480,
                    height: 506,
                    context: self,
                    content: template("dataFormTpl"),
                    onShow: function () {
                        global.get("/web/userManage/roleListAll",response=>{
                            var data = [];
                            response.data.roles.forEach(element=>{
                                var item = {};
                                item.id=element.id;
                                item.text=element.name;
                                data.push(item)
                            })
                            $('#roleId').select2({
                                //  minimumResultsForSearch设置为-1，去除搜索框 
                                minimumResultsForSearch:-1,
                                placeholder:"请选择",
                                data:data
                            });
                        })
                        $('#status').select2({
                            //  minimumResultsForSearch设置为-1，去除搜索框 
                            minimumResultsForSearch:-1,
                            placeholder:"请选择",
                            data: [
                                {
                                    id: 0,
                                    text: '未锁定',
                                    select:true
                                },
                                {
                                    id: 1,
                                    text: '已锁定'
                                }
                            ]
                        });
                    },
                    onClosed: function () {
                        if ($("#_idlg_mask_").length > 0) {
                            $("#_idlg_mask_").remove();
                        }
                    },
                    button: [{
                        id: "mybtn1",
                        label: "确定",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            var data= {};
                            data.roleId = $("#roleId").val()
                            data.userName =$("#userName").val()
                            data.plaintextPassword = $("#plaintextPassword").val()
                            if($("#plaintextPassword")!=null && data.plaintextPassword!=$("#plaintextPassword1").val()){
                                alert("密码不一致")
                                return;
                            }
                            if(data.plaintextPassword==null || data.plaintextPassword.trim()==""){
                                alert("登录密码不能为空")
                                return;
                            }
                            data.locked = $("#status").val()
                            data.description = $("#description").val()
                            if(data.userName==null || data.userName.trim()==""){
                                alert("用户名不能为空")
                                return;
                            }
                            global.post("/web/userManage/saveOrUpdate",response=>{
                                if(response.success){
                                    app.initTable();
                                }else{
                                    alert(response.message)
                                }
                            },JSON.stringify(data))
                        }
                    },
                        {
                            id: "mybtn2",
                            label: "取消",
                            intent: "default",
                            click: function () {
                                this.close();
                            }
                        }
                    ],
                });
            })
            // 编辑弹窗
            $(document).on("click", ".editData", function () {
                var nodeDetail = JSON.parse($(this).parents("tr").data("nodeDetail"));
                Dialog.open({
                    title: "修改",
                    theme: "formDialog",
                    width: 480,
                    height: 506,
                    context: self,
                    content: template("dataFormTpl",nodeDetail),
                    onShow: function () {
                        global.get("/web/userManage/roleListAll",response=>{
                            var data = [];
                            response.data.roles.forEach(element=>{
                                var item = {};
                                item.id=element.id;
                                item.text=element.name;
                                if(nodeDetail.roleName==item.text){
                                    item.selected=true
                                }
                                data.push(item)
                            })
                            $('#roleId').select2({
                                //  minimumResultsForSearch设置为-1，去除搜索框 
                                minimumResultsForSearch:-1,
                                placeholder:"请选择",
                                data:data
                            });
                            $('#status').select2({
                                //  minimumResultsForSearch设置为-1，去除搜索框 
                                minimumResultsForSearch:-1,
                                placeholder:"请选择",
                                data: [
                                    {
                                        id: 0,
                                        text: '未锁定',
                                        selected:nodeDetail.locked==0
                                    },
                                    {
                                        id: 1,
                                        text: '已锁定',
                                        selected:nodeDetail.locked==1
                                    }
                                ]
                            });
                        })
                        // 下拉框回显
                        $("#dept").val("1").trigger("change");
                        $("#status").val("2").trigger("change");
                    },
                    onClosed: function () {
                        if ($("#_idlg_mask_").length > 0) {
                            $("#_idlg_mask_").remove();
                        }
                    },
                    button: [{
                        id: "mybtn1",
                        label: "确定",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            var data= {};
                            data.id = $("#userId").val()
                            data.roleId = $("#roleId").val()
                            data.userName =$("#userName").val()
                            data.locked = $("#status").val()
                            data.description = $("#description").val()
                            if(data.userName==null || data.userName.trim()==""){
                                alert("用户名不能为空")
                                return;
                            }
                            global.post("/web/userManage/saveOrUpdate",response=>{
                                if(response.success){
                                    app.initTable();
                                }else{
                                    alert(response.message)
                                }
                            },JSON.stringify(data))
                        }
                    },
                        {
                            id: "mybtn2",
                            label: "取消",
                            intent: "default",
                            click: function () {
                                this.close();
                            }
                        }
                    ]
                });
            })

            // 编辑弹窗
            $(document).on("click", ".modifyPassword", function () {
                var nodeDetail = JSON.parse($(this).parents("tr").data("nodeDetail"));
                Dialog.open({
                    title: "修改",
                    theme: "formDialog",
                    width: 480,
                    height: 506,
                    context: self,
                    content: template("modifyPasswordFormTpl",nodeDetail),
                    onClosed: function () {
                        if ($("#_idlg_mask_").length > 0) {
                            $("#_idlg_mask_").remove();
                        }
                    },
                    button: [{
                        id: "mybtn1",
                        label: "确定",
                        intent: "primary",
                        focus: true,
                        click: function () {
                            var data= {};
                            data.id = $("#userId1").val()
                            data.plaintextPassword = $("#plaintextPassword2").val()
                            if($("#plaintextPassword2")!=null && data.plaintextPassword!=$("#plaintextPassword3").val()){
                                alert("密码不一致")
                                return;
                            }
                            if(data.plaintextPassword==null || data.plaintextPassword.trim()==""){
                                alert("登录密码不能为空")
                                return;
                            }
                            global.post("/web/userManage/modifyPassword",response=>{
                                if(response.success){
                                    app.initTable();
                                }else{
                                    alert(response.message)
                                }
                            },JSON.stringify(data))
                        }
                    },
                        {
                            id: "mybtn2",
                            label: "取消",
                            intent: "default",
                            click: function () {
                                this.close();
                            }
                        }
                    ]
                });
            })
            // 删除弹窗
            $(document).on("click", ".delData", function () {
                var userId = $(this).attr("userId");
                Dialog.open({
                    title: "<span class='aidicon aidicon-alert-circle-outline aidicon-warning'></span><span class='lineClamp2'>确认删除信息</span>",
                    width: 420,
                    height: 'auto',
                    modal: true,
                    content:'<div class="padding-left-large-5">确认需要删除选择的用户吗？删除后不可恢复。</div>',
                    button: [
                        {id:"mybtn1", label:"确认", intent:"primary", focus:true, click:function(){
                            global.delete("/web/userManage/delete/"+userId,response=>{
                                if(response.success){
                                    app.initTable();
                                }else{
                                    alert(response.message)
                                }
                            })
                        }},
                        {id:"mybtn2", label:"取消", click:function(){}}
                    ]
                });
            })
            //搜索按钮
            $(document).on("click","#searchBtn",function(){
                app.initTable();
            })
            // 关联弹窗
            $(document).on("click", ".relateData", function () {
                var userId = $(this).attr("userId");
                var list = [];
                global.get("/admin/user/granted/"+userId,response=>{
                    response.data.projects.forEach(element=>{
                        var item={};
                        item.value = element.projectId;
                        item.name=element.projectName;
                        item.flag = element.granted;
                        list.push(item);
                    })
                    Dialog.open({
                        title: "关联项目",
                        theme: "relateDialog",
                        width: 480,
                        height: 506,
                        context: self,
                        content: template("relateTpl",list),
                        onShow: function () {
                        },
                        onClosed: function () {
                            if ($("#_idlg_mask_").length > 0) {
                                $("#_idlg_mask_").remove();
                            }
                        },
                        button: [{
                            id: "mybtn1",
                            label: "确定",
                            intent: "primary",
                            focus: true,
                            click: function () {
                                var input = $("input[type='checkbox']")
                                var ids = [];
                                for(var i=0;i<input.length;i++){
                                    if($(input[i]).is(":checked")){
                                        ids.push($(input[i]).val())
                                    }
                                }
                                var data = {};
                                data.id = userId;
                                data.projectIds = ids;
                                console.log(data)
                                global.post("/web/userManage/grant?userId="+userId+"&projectIds="+ids,response=>{
                                    if(response.success){
                                        app.initTable();
                                    }else{
                                        alert(response.message)
                                    }
                                });
                            }
                        },
                            {
                                id: "mybtn2",
                                label: "取消",
                                intent: "default",
                                click: function () {
                                    this.close();
                                }
                            }
                        ]
                    });
                })
            })
            // 全选
            $(document).on("click", "#selectAll", function() {
                $(".relateDialog li .checkbox").each(function (i, v) {
                    $(v).find("input[type='checkbox']").prop("checked", "checked");
                });
            })
            window.onresize = function () {
                // getTime.resize();
            };
        },

    };
    return app;
});